package main

import (
	"time"
	"fmt"
	"os"
	"encoding/json"
	"log"

	// "net/rpc"
	// "net/http"
)

type master struct {
	arr []string
	X int
	name string
}

type KeyValue struct {
	Key   string
	Value string
}

// Values用来测试map作为方法接受者，是否改变自己（是）
type Values map[string][]string

func (v Values) Get(key string) string {
	if vs := v[key]; len(vs) > 0 {
		return vs[0]
	}
	return ""
}

func (v Values) Add(key ,value string) {
	v[key] = append(v[key], value)
}

func methodReceiver(){
	m := Values{"hello": {"en", "ch"}}
	m.Add("item", "1")
	m.Add("item", "2")
	fmt.Println(m.Get("item"))
}

func main() {
	methodReceiver()
	// waitorgo()
	// maptest()
	// timeTest()

	// writeJson()

	// var count uint16 = 3
	// if count == 3 {
	// 	fmt.Println("heloo")
	// }
	// arr := make([]bool, 3)
	// fmt.Println(arr[2])
	// slice2d()
	// ntask := make([]int, 4)
	// fmt.Println(ntask[1]) // 0

	// ma := master{arr: make([]string, 0, 3), X: 12}
	// fmt.Println(len(ma.name))
	
	// ma.arr = append(ma.arr, "hello")
	// ma.arr = append(ma.arr, "wordl")
	// fmt.Println(len(ma.arr))
	// fmt.Println(ma.X)
	// fmt.Println(ma.arr[0])
	// ma.arr = ma.arr[1:]
	// fmt.Println(ma.arr[0])
}

func waitorgo(){
	shutdown := make(chan bool)
	go func(shutdown chan<- bool) {
		time.Sleep(time.Second * 3)
		shutdown <- true
	}(shutdown)

	go func() {
		for {
			fmt.Println("working")
			time.Sleep(time.Second)
		}
	}()
	<- shutdown
	fmt.Println("outside function end")
}

func maptest(){
	timer := make(map[int]string)
	timer[0] = "ni"
	timer[1] = "hello"
	timer[3] = "stri"
	for k, v := range timer {
		fmt.Printf("%v, %v\n", k, v)
		if k == 1 {
			delete(timer, 1)
		}
	}
	fmt.Println(timer)
}

func timeTest(){
	curtime := time.Now().Unix()
	time.Sleep(time.Second)
	fmt.Println(time.Now().Unix() - curtime)
}


func writeJson(){
	kva := []KeyValue{}
	kva = append(kva, KeyValue{"1", "hello"})
	kva = append(kva, KeyValue{"2", "world"})

	os.Mkdir("output", os.ModePerm)

	dst, _ := os.OpenFile("output/dst.txt", os.O_RDWR|os.O_CREATE|os.O_APPEND,0644)
	defer dst.Close()

	// dst, err := os.Create("dst.txt")
	// if err != nil {
	// 	fmt.Printf("got error when create new file : %v", err)
	// 	return
	// }
	// defer dst.Close()

	// 以json格式写入文件
	enc := json.NewEncoder(dst)
	for _, kv := range kva {
		err := enc.Encode(&kv)
		if err != nil {
			log.Fatal("writing error")
		}
	}
}

func slice2d() {
	groups := make([][]int, 5)
	for i := range groups {
		groups[i] = make([]int, 3)
	}
	groups[4][2] = 1
	fmt.Println(groups[3][2])
}